package com.nj.liandi.gulimall.order.web;

import com.nj.liandi.common.exception.NoStockException;
import com.nj.liandi.gulimall.order.service.OrderService;
import com.nj.liandi.gulimall.order.vo.OrderConfirmVo;
import com.nj.liandi.gulimall.order.vo.OrderSubmitVo;
import com.nj.liandi.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    /*
     * description: 去结算确认页
     * version: 1.0
     * date: 2021/10/29 15:07
     * author: maizj
     * param: [model]
     * @return java.lang.String
     * */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo =orderService.confirmOrder();
        model.addAttribute("orderConfirmData",confirmVo);
        return "confirm";
    }

    /*
     * description: 下单功能
     * version: 1.0
     * date: 2021/10/29 15:08
     * author: maizj
     * param: [vo]
     * @return java.lang.String
     * */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){
        try {
            SubmitOrderResponseVo submitOrder=orderService.submitOrder(vo);
            if (submitOrder.getCode()==0) {
                //下单成功
                model.addAttribute("SubmitOrderResp",submitOrder);
                return "pay";
            }else {
                String msg = "下单失败";
                switch (submitOrder.getCode()){
                    case 1: msg +="订单信息过期,请刷新再次提交"; break;
                    case 2: msg +="订单商品价格发生变化,请确认后再次提交"; break;
                    case 3: msg +="商品库存不足";break;
                }
                redirectAttributes.addFlashAttribute("msg",msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }
        }catch (NoStockException e){
            redirectAttributes.addFlashAttribute("msg",e.getMsg());
            return "redirect:http://order.gulimall.com/toTrade";
        }

    }
}
